import React, { useEffect, useRef, useState } from "react";
import "./EarthPolar.css";
import { PolarProjectionUtils } from "../utils/polarProjection";
import { LocationPoint, DetectionPoint, LatLngRect, DetectionPointWithApiFields } from "../types/earth";
import { rectIntersects, pointIntersectsRect, getCorrectLngRange } from "../utils/earthUtils";

interface EarthPolarProps {
  polarType: "north" | "south";
  locationPoints?: LocationPoint[];
  detectionPoints?: DetectionPointWithApiFields[];
  rects?: LatLngRect[];
  onCoordinateClick?: (coord: { lat: number; lng: number } | null) => void;
  onCoordinateHover?: (coord: { lat: number; lng: number } | null) => void;
  onLocationClick?: (location: LocationPoint | null) => void;
  onLocationHover?: (location: LocationPoint | null) => void;
  onDetectionPointClick?: (detectionPoint: DetectionPointWithApiFields | null) => void;
  onDetectionPointHover?: (detectionPoint: DetectionPointWithApiFields | null) => void;
  onRectClick?: (rect: LatLngRect | null) => void;
  onRectHover?: (rect: LatLngRect | null) => void;
  onSelectionChange?: (selectionRect: LatLngRect | null) => void;
  onSelectionEnd?: (
    selectionRect: LatLngRect | null,
    intersectingRects: LatLngRect[],
    intersectingDetectionPoints: DetectionPointWithApiFields[]
  ) => void;
  externalSelection?: LatLngRect | null;
  simulatedMetaKey?: boolean;
}

const EarthPolar: React.FC<EarthPolarProps> = ({
  polarType,
  locationPoints = [],
  detectionPoints = [],
  rects = [],
  onCoordinateClick,
  onCoordinateHover,
  onLocationClick,
  onLocationHover,
  onDetectionPointClick,
  onDetectionPointHover,
  onRectClick,
  onRectHover,
  onSelectionChange,
  onSelectionEnd,
  externalSelection,
  simulatedMetaKey = false,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [scale, setScale] = useState(1);
  const [panX, setPanX] = useState(0);
  const [panY, setPanY] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [imageLoaded, setImageLoaded] = useState(false);
  const [hoveredLocation, setHoveredLocation] = useState<LocationPoint | null>(null);
  const [hoveredDetectionPoint, setHoveredDetectionPoint] = useState<DetectionPointWithApiFields | null>(null);
  const [hoveredRect, setHoveredRect] = useState<LatLngRect | null>(null);

  // 选区相关状态
  const [isSelecting, setIsSelecting] = useState(false);
  const [selectionClickCount, setSelectionClickCount] = useState(0);
  const [selectionStart, setSelectionStart] = useState<{ lat: number; lng: number } | null>(null);
  const [selectionEnd, setSelectionEnd] = useState<{ lat: number; lng: number } | null>(null);
  const [intersectedRects, setIntersectedRects] = useState<boolean[]>([]);
  const [intersectedDetectionPoints, setIntersectedDetectionPoints] = useState<boolean[]>([]);

  // 使用ref来跟踪selectionClickCount的当前值，避免状态更新的异步问题
  const selectionClickCountRef = useRef(0);
  const selectionStartRef = useRef<{ lat: number; lng: number } | null>(null);

  // 使用ref来存储最新的locationPoints，避免闭包问题
  const locationPointsRef = useRef(locationPoints);
  const detectionPointsRef = useRef(detectionPoints);
  const rectsRef = useRef(rects);
  const simulatedMetaKeyRef = useRef(simulatedMetaKey);

  // 更新ref值
  useEffect(() => {
    locationPointsRef.current = locationPoints;
  }, [locationPoints]);

  useEffect(() => {
    detectionPointsRef.current = detectionPoints;
  }, [detectionPoints]);

  useEffect(() => {
    rectsRef.current = rects;
  }, [rects]);

  useEffect(() => {
    simulatedMetaKeyRef.current = simulatedMetaKey;
  }, [simulatedMetaKey]);

  // 同步selectionClickCountRef的值
  useEffect(() => {
    selectionClickCountRef.current = selectionClickCount;
  }, [selectionClickCount]);

  // 同步selectionStartRef的值
  useEffect(() => {
    selectionStartRef.current = selectionStart;
  }, [selectionStart]);

  // 跟踪事件绑定状态，避免重复绑定
  const eventsBoundRef = useRef(false);
  // 使用ref来获取最新的拖拽状态
  const isDraggingRef = useRef(false);
  const dragOffsetRef = useRef<{ x: number; y: number } | null>(null);

  // 使用useRef来获取最新的状态值
  const scaleRef = useRef(scale);
  const panXRef = useRef(panX);
  const panYRef = useRef(panY);
  const imageLoadedRef = useRef(imageLoaded);
  const imageRef = useRef<HTMLImageElement | null>(null);
  const animationFrameRef = useRef<number | null>(null);

  // 更新ref值
  useEffect(() => {
    scaleRef.current = scale;
  }, [scale]);

  useEffect(() => {
    panXRef.current = panX;
  }, [panX]);

  useEffect(() => {
    panYRef.current = panY;
  }, [panY]);

  useEffect(() => {
    imageLoadedRef.current = imageLoaded;
  }, [imageLoaded]);

  // 坐标转换辅助函数
  const getCoordinateFromScreen = (screenX: number, screenY: number) => {
    const canvas = canvasRef.current;
    if (!canvas) return null;

    return PolarProjectionUtils.screenToLatLng(
      screenX,
      screenY,
      canvas.width,
      canvas.height,
      panXRef.current,
      panYRef.current,
      scaleRef.current,
      polarType
    );
  };

  // 检查点击位置是否在地点、探测点或矩形区域上
  const checkPointClick = (screenX: number, screenY: number) => {
    const canvas = canvasRef.current;
    if (!canvas) return null;

    // 检查地点
    for (const location of locationPointsRef.current) {
      const screenPos = PolarProjectionUtils.latLngToScreen(
        location.center_latitude,
        location.center_longitude,
        canvas.width,
        canvas.height,
        panXRef.current,
        panYRef.current,
        scaleRef.current,
        polarType
      );

      if (screenPos) {
        const distance = Math.sqrt(Math.pow(screenX - screenPos.x, 2) + Math.pow(screenY - screenPos.y, 2));
        if (distance <= 20) {
          // 增加到20像素的点击范围
          return { type: "location", data: location };
        }
      }
    }

    // 检查探测点
    for (const detectionPoint of detectionPointsRef.current) {
      const screenPos = PolarProjectionUtils.latLngToScreen(
        detectionPoint.latitude,
        detectionPoint.longitude,
        canvas.width,
        canvas.height,
        panXRef.current,
        panYRef.current,
        scaleRef.current,
        polarType
      );

      if (screenPos) {
        const distance = Math.sqrt(Math.pow(screenX - screenPos.x, 2) + Math.pow(screenY - screenPos.y, 2));
        if (distance <= 10) {
          // 10像素的点击范围
          return { type: "detection", data: detectionPoint };
        }
      }
    }

    // 检查矩形区域
    for (const rect of rectsRef.current) {
      if (
        PolarProjectionUtils.isInPolarRange(rect.minLat, rect.minLng, polarType) ||
        PolarProjectionUtils.isInPolarRange(rect.maxLat, rect.maxLng, polarType)
      ) {
        // 检查点击是否在矩形区域内
        const topLeft = PolarProjectionUtils.latLngToScreen(
          rect.maxLat,
          rect.minLng,
          canvas.width,
          canvas.height,
          panXRef.current,
          panYRef.current,
          scaleRef.current,
          polarType
        );
        const bottomRight = PolarProjectionUtils.latLngToScreen(
          rect.minLat,
          rect.maxLng,
          canvas.width,
          canvas.height,
          panXRef.current,
          panYRef.current,
          scaleRef.current,
          polarType
        );

        if (topLeft && bottomRight) {
          const minX = Math.min(topLeft.x, bottomRight.x);
          const maxX = Math.max(topLeft.x, bottomRight.x);
          const minY = Math.min(topLeft.y, bottomRight.y);
          const maxY = Math.max(topLeft.y, bottomRight.y);

          if (screenX >= minX && screenX <= maxX && screenY >= minY && screenY <= maxY) {
            return { type: "rect", data: rect };
          }
        }
      }
    }

    return null;
  };

  // 处理鼠标点击事件
  const handleCanvasClick = (e: MouseEvent) => {
    // 如果正在拖拽，不处理点击事件
    if (isDraggingRef.current) return;

    const rect = canvasRef.current?.getBoundingClientRect();
    if (!rect) return;

    const screenX = e.clientX - rect.left;
    const screenY = e.clientY - rect.top;

    // 检查是否在选区模式（Meta键或模拟Meta键）
    const selectionMode = e.metaKey || simulatedMetaKeyRef.current;

    if (selectionMode) {
      const coord = getCoordinateFromScreen(screenX, screenY);
      if (coord) {
        const currentClickCount = selectionClickCountRef.current;
        if (currentClickCount === 0) {
          // 第一次点击，开始选区
          setSelectionStart(coord);
          setSelectionEnd(coord);
          setSelectionClickCount(1);
          setIsSelecting(true);
        } else if (currentClickCount === 1) {
          // 第二次点击，完成选区
          setSelectionEnd(coord);
          setSelectionClickCount(0);

          // 使用ref获取最新的selectionStart值
          const currentSelectionStart = selectionStartRef.current;

          // 计算最终的选区
          if (currentSelectionStart) {
            const lngRange = getCorrectLngRange(currentSelectionStart.lng, coord.lng);
            const finalSelectionRect: LatLngRect = {
              minLat: Math.min(currentSelectionStart.lat, coord.lat),
              maxLat: Math.max(currentSelectionStart.lat, coord.lat),
              minLng: lngRange.minLng,
              maxLng: lngRange.maxLng,
            };

            // 查找与选区相交的rects
            const intersectingRects = rectsRef.current.filter((rect) => rectIntersects(rect, finalSelectionRect));

            // 查找与选区相交的探测点
            const intersectingDetectionPoints = detectionPointsRef.current.filter((point) => {
              return pointIntersectsRect(
                { lat: point.center_latitude, lng: point.center_longitude },
                finalSelectionRect
              );
            });

            // 调用选区结束回调
            if (onSelectionEnd) {
              onSelectionEnd(finalSelectionRect, intersectingRects, intersectingDetectionPoints);
            }
          }

          // 重置选区状态
          setIsSelecting(false);
          setSelectionStart(null);
          setSelectionEnd(null);
        }
      }
      return;
    }

    // 首先检查是否点击了地点、探测点或矩形区域
    const clickedPoint = checkPointClick(screenX, screenY);
    if (clickedPoint) {
      if (clickedPoint.type === "location" && onLocationClick) {
        onLocationClick(clickedPoint.data as LocationPoint);
      } else if (clickedPoint.type === "detection" && onDetectionPointClick) {
        onDetectionPointClick(clickedPoint.data as DetectionPointWithApiFields);
      } else if (clickedPoint.type === "rect" && onRectClick) {
        onRectClick(clickedPoint.data as LatLngRect);
      }
      return;
    }

    // 如果没有点击到地点或探测点，则处理坐标点击
    const coord = getCoordinateFromScreen(screenX, screenY);
    if (onCoordinateClick) {
      onCoordinateClick(coord);
    }
  };

  // 检查悬停位置是否在地点、探测点或矩形区域上
  const checkPointHover = (screenX: number, screenY: number) => {
    const canvas = canvasRef.current;
    if (!canvas) return null;

    // 检查地点
    for (const location of locationPoints) {
      const screenPos = PolarProjectionUtils.latLngToScreen(
        location.center_latitude,
        location.center_longitude,
        canvas.width,
        canvas.height,
        panXRef.current,
        panYRef.current,
        scaleRef.current,
        polarType
      );

      if (screenPos) {
        const distance = Math.sqrt(Math.pow(screenX - screenPos.x, 2) + Math.pow(screenY - screenPos.y, 2));
        if (distance <= 8) {
          // 8像素的悬停范围
          return { type: "location", data: location };
        }
      }
    }

    // 检查探测点
    for (const detectionPoint of detectionPointsRef.current) {
      const screenPos = PolarProjectionUtils.latLngToScreen(
        detectionPoint.latitude,
        detectionPoint.longitude,
        canvas.width,
        canvas.height,
        panXRef.current,
        panYRef.current,
        scaleRef.current,
        polarType
      );

      if (screenPos) {
        const distance = Math.sqrt(Math.pow(screenX - screenPos.x, 2) + Math.pow(screenY - screenPos.y, 2));
        if (distance <= 8) {
          // 8像素的悬停范围
          return { type: "detection", data: detectionPoint };
        }
      }
    }

    // 检查矩形区域
    for (const rect of rectsRef.current) {
      if (
        PolarProjectionUtils.isInPolarRange(rect.minLat, rect.minLng, polarType) ||
        PolarProjectionUtils.isInPolarRange(rect.maxLat, rect.maxLng, polarType)
      ) {
        // 检查悬停是否在矩形区域内
        const topLeft = PolarProjectionUtils.latLngToScreen(
          rect.maxLat,
          rect.minLng,
          canvas.width,
          canvas.height,
          panXRef.current,
          panYRef.current,
          scaleRef.current,
          polarType
        );
        const bottomRight = PolarProjectionUtils.latLngToScreen(
          rect.minLat,
          rect.maxLng,
          canvas.width,
          canvas.height,
          panXRef.current,
          panYRef.current,
          scaleRef.current,
          polarType
        );

        if (topLeft && bottomRight) {
          const minX = Math.min(topLeft.x, bottomRight.x);
          const maxX = Math.max(topLeft.x, bottomRight.x);
          const minY = Math.min(topLeft.y, bottomRight.y);
          const maxY = Math.max(topLeft.y, bottomRight.y);

          if (screenX >= minX && screenX <= maxX && screenY >= minY && screenY <= maxY) {
            return { type: "rect", data: rect };
          }
        }
      }
    }

    return null;
  };

  // 处理鼠标移动事件（用于悬停显示坐标）
  const handleCanvasMouseMove = (e: MouseEvent) => {
    const rect = canvasRef.current?.getBoundingClientRect();
    if (!rect) return;

    const screenX = e.clientX - rect.left;
    const screenY = e.clientY - rect.top;

    // 选区模式下，实时更新选区预览
    if (isSelecting && selectionStart) {
      const coord = getCoordinateFromScreen(screenX, screenY);
      if (coord) {
        setSelectionEnd(coord);

        // 实时更新选区状态
        if (onSelectionChange) {
          const lngRange = getCorrectLngRange(selectionStart.lng, coord.lng);
          const selectionRect: LatLngRect = {
            minLat: Math.min(selectionStart.lat, coord.lat),
            maxLat: Math.max(selectionStart.lat, coord.lat),
            minLng: lngRange.minLng,
            maxLng: lngRange.maxLng,
          };
          onSelectionChange(selectionRect);
        }
      }
      return;
    }

    // 首先检查是否悬停在地点、探测点或矩形区域上
    const hoveredPoint = checkPointHover(screenX, screenY);
    if (hoveredPoint) {
      if (hoveredPoint.type === "location") {
        const location = hoveredPoint.data as LocationPoint;
        if (hoveredLocation !== location) {
          setHoveredLocation(location);
          setHoveredDetectionPoint(null);
          setHoveredRect(null);
          if (onLocationHover) {
            onLocationHover(location);
          }
        }
      } else if (hoveredPoint.type === "detection") {
        const detectionPoint = hoveredPoint.data as DetectionPointWithApiFields;
        if (hoveredDetectionPoint !== detectionPoint) {
          setHoveredDetectionPoint(detectionPoint);
          setHoveredLocation(null);
          setHoveredRect(null);
          if (onDetectionPointHover) {
            onDetectionPointHover(detectionPoint);
          }
        }
      } else if (hoveredPoint.type === "rect") {
        const rect = hoveredPoint.data as LatLngRect;
        if (hoveredRect !== rect) {
          setHoveredRect(rect);
          setHoveredLocation(null);
          setHoveredDetectionPoint(null);
          if (onRectHover) {
            onRectHover(rect);
          }
        }
      }
      return;
    }

    // 如果没有悬停到任何对象，则处理坐标悬停
    if (hoveredLocation || hoveredDetectionPoint || hoveredRect) {
      setHoveredLocation(null);
      setHoveredDetectionPoint(null);
      setHoveredRect(null);
      if (onLocationHover) onLocationHover(null);
      if (onDetectionPointHover) onDetectionPointHover(null);
      if (onRectHover) onRectHover(null);
    }

    const coord = getCoordinateFromScreen(screenX, screenY);
    if (onCoordinateHover) {
      onCoordinateHover(coord);
    }
  };

  // 预加载图片
  useEffect(() => {
    const img = new Image();
    img.onload = () => {
      imageRef.current = img;
      setImageLoaded(true);
    };
    img.src = "/test/jidi.png";
  }, []);

  // 通用的绘制矩形区域方法
  const drawRect = (
    ctx: CanvasRenderingContext2D,
    rect: LatLngRect,
    width: number,
    height: number,
    polarType: "north" | "south",
    style: {
      strokeStyle: string;
      fillStyle: string;
      lineWidth: number;
    },
    showName: boolean = true
  ) => {
    // 检查矩形是否在极区范围内
    const inRange1 = PolarProjectionUtils.isInPolarRange(rect.minLat, rect.minLng, polarType);
    const inRange2 = PolarProjectionUtils.isInPolarRange(rect.maxLat, rect.maxLng, polarType);

    if (!inRange1 && !inRange2) {
      return; // 不在极区范围内，不绘制
    }

    // 计算极地投影的中心和半径
    const centerX = width / 2 + panXRef.current;
    const centerY = height / 2 + panYRef.current;
    const maxRadius = Math.min(width, height) / 2 - 20;

    // 生成矩形的边界点，沿着经纬度线
    const points: { x: number; y: number }[] = [];

    // 1. 上边（最大纬度线）- 从左上角到右上角
    const topLat = rect.maxLat;
    const lngStep = Math.max((rect.maxLng - rect.minLng) / 20, 0.001); // 确保步长不为0
    for (let lng = rect.minLng; lng <= rect.maxLng; lng += lngStep) {
      const distance = ((90 - Math.abs(topLat)) / 30) * maxRadius;
      // 将距离限制在极区边界内
      const clampedDistance = Math.min(distance, maxRadius);
      const angle = (lng * Math.PI) / 180;
      const x = centerX + clampedDistance * Math.cos(angle) * scaleRef.current;
      const y = centerY + (polarType === "south" ? -1 : 1) * clampedDistance * Math.sin(angle) * scaleRef.current;
      points.push({ x, y });
    }

    // 2. 右边（最大经度线）- 从右上角到右下角
    const rightLng = rect.maxLng;
    const latStep = Math.max((rect.maxLat - rect.minLat) / 20, 0.001); // 确保步长不为0
    for (let lat = rect.maxLat; lat >= rect.minLat; lat -= latStep) {
      const distance = ((90 - Math.abs(lat)) / 30) * maxRadius;
      // 将距离限制在极区边界内
      const clampedDistance = Math.min(distance, maxRadius);
      const angle = (rightLng * Math.PI) / 180;
      const x = centerX + clampedDistance * Math.cos(angle) * scaleRef.current;
      const y = centerY + (polarType === "south" ? -1 : 1) * clampedDistance * Math.sin(angle) * scaleRef.current;
      points.push({ x, y });
    }

    // 3. 下边（最小纬度线）- 从右下角到左下角
    const bottomLat = rect.minLat;
    for (let lng = rect.maxLng; lng >= rect.minLng; lng -= lngStep) {
      const distance = ((90 - Math.abs(bottomLat)) / 30) * maxRadius;
      // 将距离限制在极区边界内
      const clampedDistance = Math.min(distance, maxRadius);
      const angle = (lng * Math.PI) / 180;
      const x = centerX + clampedDistance * Math.cos(angle) * scaleRef.current;
      const y = centerY + (polarType === "south" ? -1 : 1) * clampedDistance * Math.sin(angle) * scaleRef.current;
      points.push({ x, y });
    }

    // 4. 左边（最小经度线）- 从左下角到左上角
    const leftLng = rect.minLng;
    for (let lat = rect.minLat; lat <= rect.maxLat; lat += latStep) {
      const distance = ((90 - Math.abs(lat)) / 30) * maxRadius;
      // 将距离限制在极区边界内
      const clampedDistance = Math.min(distance, maxRadius);
      const angle = (leftLng * Math.PI) / 180;
      const x = centerX + clampedDistance * Math.cos(angle) * scaleRef.current;
      const y = centerY + (polarType === "south" ? -1 : 1) * clampedDistance * Math.sin(angle) * scaleRef.current;
      points.push({ x, y });
    }

    // 绘制路径
    if (points.length > 0) {
      ctx.strokeStyle = style.strokeStyle;
      ctx.fillStyle = style.fillStyle;
      ctx.lineWidth = style.lineWidth;

      ctx.beginPath();
      ctx.moveTo(points[0].x, points[0].y);
      for (let i = 1; i < points.length; i++) {
        ctx.lineTo(points[i].x, points[i].y);
      }
      ctx.closePath();

      ctx.fill();
      ctx.stroke();

      // 绘制矩形名称
      if (showName && rect.name && scaleRef.current > 0.5) {
        // 计算矩形的中心点
        const centerX = points.reduce((sum, p) => sum + p.x, 0) / points.length;
        const centerY = points.reduce((sum, p) => sum + p.y, 0) / points.length;

        ctx.fillStyle = "#333";
        ctx.font = `${12 / scaleRef.current}px Arial`;
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";

        // 绘制文字阴影
        ctx.fillStyle = "#000";
        ctx.fillText(rect.name, centerX + 1, centerY + 1);

        // 绘制文字
        ctx.fillStyle = "#fff";
        ctx.fillText(rect.name, centerX, centerY);
      }
    }
  };

  // 绘制极区地图
  const render = () => {
    const canvas = canvasRef.current;
    if (!canvas || !imageLoadedRef.current || !imageRef.current) return;

    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    const width = canvas.width;
    const height = canvas.height;

    // 清空画布
    ctx.clearRect(0, 0, width, height);

    // 保存画布状态
    ctx.save();

    // 应用变换
    ctx.translate(width / 2 + panXRef.current, height / 2 + panYRef.current);
    ctx.scale(scaleRef.current, scaleRef.current);

    // 根据极区类型调整显示方向
    if (polarType === "south") {
      // 南极需要Y轴翻转，因为从南极看是相反的
      ctx.scale(1, -1);
    }

    const radius = Math.min(width, height) / 2 - 20;

    // 绘制圆形底图
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, 2 * Math.PI);
    ctx.clip();

    // 绘制图片
    ctx.drawImage(imageRef.current, -radius, -radius, radius * 2, radius * 2);

    // 绘制极区边界
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, 2 * Math.PI);
    ctx.strokeStyle = "#333";
    ctx.lineWidth = 2 / scale;
    ctx.stroke();

    ctx.globalAlpha = 1;

    // 绘制探测点标记
    detectionPoints.forEach((detectionPoint) => {
      const screenPos = PolarProjectionUtils.latLngToScreen(
        detectionPoint.latitude,
        detectionPoint.longitude,
        width,
        height,
        panXRef.current,
        panYRef.current,
        scaleRef.current,
        polarType
      );

      if (screenPos) {
        // 检查是否在极区范围内
        if (PolarProjectionUtils.isInPolarRange(detectionPoint.latitude, detectionPoint.longitude, polarType)) {
          // 绘制探测点标记
          ctx.beginPath();
          ctx.arc(screenPos.x, screenPos.y, 5 / scaleRef.current, 0, 2 * Math.PI);
          ctx.fillStyle = hoveredDetectionPoint === detectionPoint ? "#ff9f43" : "#feca57";
          ctx.fill();
          ctx.strokeStyle = "#fff";
          ctx.lineWidth = 2 / scaleRef.current;
          ctx.stroke();

          // 绘制探测点名称
          if (scaleRef.current > 0.5) {
            // 只在放大时显示名称
            ctx.fillStyle = "#333";
            ctx.font = `${10 / scaleRef.current}px Arial`;
            ctx.textAlign = "center";
            ctx.textBaseline = "top";
            ctx.fillText(detectionPoint.name, screenPos.x, screenPos.y + 8 / scaleRef.current);
          }
        }
      }
    });

    // 恢复画布状态
    ctx.restore();

    // 绘制矩形区域 - 使用通用方法
    rects.forEach((rect) => {
      const isHovered = hoveredRect === rect;

      // 检查是否与当前选区相交
      let isIntersecting = false;
      if (isSelecting && selectionStart && selectionEnd) {
        const selectionRect = {
          minLat: Math.min(selectionStart.lat, selectionEnd.lat),
          maxLat: Math.max(selectionStart.lat, selectionEnd.lat),
          minLng: Math.min(selectionStart.lng, selectionEnd.lng),
          maxLng: Math.max(selectionStart.lng, selectionEnd.lng),
        };
        isIntersecting = rectIntersects(rect, selectionRect);
      } else if (externalSelection) {
        isIntersecting = rectIntersects(rect, externalSelection);
      }

      // 根据状态设置样式：相交时红色边框无填充，悬停时红色，正常时绿色
      let style;
      if (isIntersecting) {
        style = {
          strokeStyle: "#ff0000",
          fillStyle: "transparent",
          lineWidth: 3,
        };
      } else if (isHovered) {
        style = {
          strokeStyle: "#ff6b6b",
          fillStyle: "rgba(255, 107, 107, 0.2)",
          lineWidth: 3,
        };
      } else {
        style = {
          strokeStyle: "#00ff00",
          fillStyle: "rgba(0, 255, 0, 0.1)",
          lineWidth: 2,
        };
      }

      drawRect(ctx, rect, width, height, polarType, style, true);
    });

    // 绘制选区 - 使用通用方法
    if (isSelecting && selectionStart && selectionEnd) {
      // 计算选区的四个角点
      const selectionRect = {
        minLat: Math.min(selectionStart!.lat, selectionEnd!.lat),
        maxLat: Math.max(selectionStart!.lat, selectionEnd!.lat),
        minLng: Math.min(selectionStart!.lng, selectionEnd!.lng),
        maxLng: Math.max(selectionStart!.lng, selectionEnd!.lng),
        name: "选区", // 添加名称，但不会显示
      };

      const style = {
        strokeStyle: "#ffcc00",
        fillStyle: "rgba(255, 204, 0, 0.1)",
        lineWidth: 2,
      };

      drawRect(ctx, selectionRect, width, height, polarType, style, false);
    } else if (!isSelecting && externalSelection) {
      // 非选区模式下，绘制外部传入的选区
      const style = {
        strokeStyle: "#ffcc00",
        fillStyle: "rgba(255, 204, 0, 0.1)",
        lineWidth: 2,
      };

      drawRect(ctx, externalSelection, width, height, polarType, style, false);
    }

    // 绘制地点标记 - 在屏幕坐标系中绘制
    locationPoints.forEach((location) => {
      const screenPos = PolarProjectionUtils.latLngToScreen(
        location.center_latitude,
        location.center_longitude,
        width,
        height,
        panXRef.current,
        panYRef.current,
        scaleRef.current,
        polarType
      );

      if (screenPos) {
        // 检查是否在极区范围内
        if (PolarProjectionUtils.isInPolarRange(location.center_latitude, location.center_longitude, polarType)) {
          // 绘制地点标记
          ctx.beginPath();
          ctx.arc(screenPos.x, screenPos.y, 6, 0, 2 * Math.PI);
          ctx.fillStyle = hoveredLocation === location ? "#ff6b6b" : "#4ecdc4";
          ctx.fill();
          ctx.strokeStyle = "#fff";
          ctx.lineWidth = 2;
          ctx.stroke();

          // 绘制地点名称
          if (scaleRef.current > 0.5) {
            // 只在放大时显示名称
            ctx.font = "12px Arial";
            ctx.textAlign = "center";
            ctx.textBaseline = "top";

            // 绘制黑色阴影
            ctx.fillStyle = "#000";
            ctx.fillText(location.name, screenPos.x + 1, screenPos.y + 11);

            // 绘制白色文字
            ctx.fillStyle = "#fff";
            ctx.fillText(location.name, screenPos.x, screenPos.y + 10);
          }
        }
      }
    });
  };

  // 初始化画布和事件绑定
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const resizeCanvas = () => {
      if (canvas.parentElement) {
        const rect = canvas.parentElement.getBoundingClientRect();
        canvas.width = rect.width;
        canvas.height = rect.height;
        // 延迟调用render，确保canvas尺寸设置完成后再绘制
        requestAnimationFrame(() => {
          render();
        });
      }
    };

    const handleWheelEvent = (e: WheelEvent) => {
      e.preventDefault();
      e.stopPropagation();

      const rect = canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;
      let newScale = Math.min(10, scaleRef.current * zoomFactor);

      // 确保地图最小尺寸不小于容器高度
      const minScale = rect.height / 800; // 800是极区地图的参考高度
      newScale = Math.max(newScale, minScale);

      // 以鼠标位置为中心进行缩放
      const scaleRatio = newScale / scaleRef.current;

      // 计算鼠标相对于画布中心的位置
      const canvasCenterX = rect.width / 2;
      const canvasCenterY = rect.height / 2;
      const mouseOffsetX = x - canvasCenterX;
      const mouseOffsetY = y - canvasCenterY;

      // 计算缩放后的新pan位置，保持鼠标位置不变
      const newPanX = panXRef.current - mouseOffsetX * (scaleRatio - 1);
      const newPanY = panYRef.current - mouseOffsetY * (scaleRatio - 1);

      // 限制边界 - 极区地图不应该超出圆形边界
      const maxRadius = Math.min(rect.width, rect.height) / 2 - 20;
      const maxPanX = maxRadius;
      const minPanX = -maxRadius;
      const maxPanY = maxRadius;
      const minPanY = -maxRadius;

      const clampedPanX = Math.max(minPanX, Math.min(maxPanX, newPanX));
      const clampedPanY = Math.max(minPanY, Math.min(maxPanY, newPanY));

      setPanX(clampedPanX);
      setPanY(clampedPanY);
      setScale(newScale);
    };

    resizeCanvas();
    window.addEventListener("resize", resizeCanvas);
    canvas.addEventListener("wheel", handleWheelEvent, { passive: false });
    canvas.addEventListener("mousedown", handleMouseDown);
    canvas.addEventListener("click", handleCanvasClick);
    canvas.addEventListener("mousemove", handleCanvasMouseMove);

    return () => {
      window.removeEventListener("resize", resizeCanvas);
      canvas.removeEventListener("wheel", handleWheelEvent);
      canvas.removeEventListener("mousedown", handleMouseDown);
      canvas.removeEventListener("click", handleCanvasClick);
      canvas.removeEventListener("mousemove", handleCanvasMouseMove);
      // 确保清理可能存在的动态绑定事件
      if (eventsBoundRef.current) {
        window.removeEventListener("mousemove", handleMouseMove);
        window.removeEventListener("mouseup", handleMouseUp);
        eventsBoundRef.current = false;
      }
    };
  }, []);

  // 绘制地图
  useEffect(() => {
    if (imageLoaded) {
      render();
    }
  }, [
    scale,
    panX,
    panY,
    polarType,
    imageLoaded,
    locationPoints,
    detectionPoints,
    rects,
    hoveredLocation,
    hoveredDetectionPoint,
    hoveredRect,
    isSelecting,
    selectionStart,
    selectionEnd,
  ]);

  // 鼠标事件处理 - 只在mousedown时开始监听move事件
  const handleMouseDown = (e: MouseEvent) => {
    const rect = canvasRef.current?.getBoundingClientRect();
    if (!rect) return;

    // 在选区模式下不触发拖拽
    if (e.metaKey || simulatedMetaKeyRef.current) {
      return;
    }

    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    // 计算鼠标相对于极区地图中心的偏移量
    const canvasCenterX = rect.width / 2;
    const canvasCenterY = rect.height / 2;
    const offsetX = x - canvasCenterX - panXRef.current;
    const offsetY = y - canvasCenterY - panYRef.current;

    setIsDragging(true);
    // 同时更新ref，确保事件处理函数能获取到最新值
    isDraggingRef.current = true;
    dragOffsetRef.current = { x: offsetX, y: offsetY };

    // 开始拖拽时动态绑定mousemove和mouseup事件（避免重复绑定）
    if (!eventsBoundRef.current) {
      window.addEventListener("mousemove", handleMouseMove);
      window.addEventListener("mouseup", handleMouseUp);
      eventsBoundRef.current = true;
    }
  };

  const handleMouseMove = (e: MouseEvent) => {
    const rect = canvasRef.current?.getBoundingClientRect();
    if (!rect) return;

    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    if (isDraggingRef.current && dragOffsetRef.current) {
      // 计算新的pan位置，保持鼠标与地图上点的相对位置不变
      const canvasCenterX = rect.width / 2;
      const canvasCenterY = rect.height / 2;
      const newPanX = x - canvasCenterX - dragOffsetRef.current.x;
      const newPanY = y - canvasCenterY - dragOffsetRef.current.y;

      // 暂时移除边界限制，测试拖动功能
      setPanX(newPanX);
      setPanY(newPanY);

      // 移动过程中不重新绘制，只更新位置
      // 绘制会在useEffect中自动触发
    }
  };

  const handleMouseUp = (_e: MouseEvent) => {
    setIsDragging(false);
    // 同时更新ref
    isDraggingRef.current = false;
    dragOffsetRef.current = null;

    // 拖拽结束时解绑mousemove和mouseup事件（避免重复解绑）
    if (eventsBoundRef.current) {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
      eventsBoundRef.current = false;
    }

    // 不再需要清理动画帧，因为移动过程中不再使用requestAnimationFrame
  };

  return (
    <div className="earth-polar-container">
      <canvas
        ref={canvasRef}
        className="earth-polar-canvas"
        style={{
          cursor: simulatedMetaKeyRef.current ? "crosshair" : isDragging ? "grabbing" : "grab",
        }}
      />
    </div>
  );
};

export default EarthPolar;
